# -*- coding: utf-8 -*-
"""
Created on Mon Nov 24 16:59:04 2014

@author: Maxim
"""
import numpy as np
from mission import Cruise, Climb
import convert
import sys
from perf_field import run_takeoff


def run_mission_analysis(ac,mis=None,showDetails=False):
    """
    calculate mission time and fuel for given aircraft and mission profile
    """
    if mis==None:
        mis = ac.mission
    nseg = mis.nMisSeg
    Wfuel = np.zeros(nseg)
    time  = np.zeros(nseg)
    wfstart = ac.mass.fuel.mass
    if showDetails:
        print 'Segment\tFuel burned\tFuel left\tTime\n================'
    for i in range(nseg):
        wf, dt, dR = mission_segment_analysis(ac,wfstart,mis,i)
        wfstart += -wf
        if showDetails:
            print '%s\t%.1f\t%.1f\t%.1f'%(mis.segmentName[i],wf,wfstart,dt/60.)
        Wfuel[i] = wf
        time[i] = dt
        mis.time[i] = dt
        mis.fuelBurned[i] = wf
        mis.distance[i] = dR
    WfuelTotal = np.sum(Wfuel)
    timeTotal = np.sum(time)
    mis.fuelFraction = mis.fuelBurned/WfuelTotal
    mis.cumFuelFraction = np.cumsum(mis.fuelFraction)
    return WfuelTotal, timeTotal, mis


def mission_segment_analysis(ac,wfstart,mis,iseg):
    name = mis.segmentName[iseg]
    data = mis[iseg]
    if name=='CLIMB':
        wf,dt,dR = climb(ac,wfstart,data)
    elif name=='CRUISE':
        wf,dt,dR = cruise(ac,wfstart,data)
    elif name=='LOITER':
        wf,dt,dR = loiter(ac,wfstart,data)
    elif name=='DESCENT':
        wf,dt,dR = 0.0, 0.0, 0.0 #TODO: No credit
    elif name=='TAKEOFF':
        wf,dt,dR = run_takeoff(ac,data[0],data[7])
    elif name=='LANDING':
        wf,dt,dR = 0.0, 0.0, 0.0 #TODO:
    else:
        print '%s analysis is not available'%name
        wf, dt = 0.0, 0.0
    return wf,dt,dR



def climb(ac,wfstart,data):
    nseg = data[7]
    hstart = data[0]
    hend = data[1]
    vStart = data[2]
    vEnd = data[3]
    Tset = data[4]
    clm = Climb(ac)
    rslt = clm.run_climb2(hstart, hend, vStart, vEnd, nseg, Tset, wfstart)
    #return rslt.fuelBurned, rslt.time, rslt.distance
    return abs(rslt.fuelBurned), abs(rslt.time), abs(rslt.distance)

def cruise(ac,wfstart,data):
    hcruise = data[0]
    vStart = data[2]
    vEnd = data[3]
    dist = data[5]
    slf = Cruise(ac)
    rslt = slf.run_cruise(hcruise,hcruise,vStart,vEnd,dist,wfstart,nSeg=data[7])
    return rslt.fuelBurned, rslt.time, rslt.distance

def loiter(ac,wfstart,data):
    hloiter = data[0]
    vloiter = data[2]
    endur = data[6]
    slf = Cruise(ac)
    rslt = slf.run_loiter(hloiter, vloiter, endur, wfstart,nSeg=data[7])
    return rslt.fuelBurned, rslt.time, rslt.distance


def get_mission_fuel(ac,mis=None,imax=20,tol=1.0,display=False):
    err = tol+1.0
    i = 0
    
    wfprev = ac.designGoals.fuelMass
    sys.stdout.write('calculating mission fuel')
    while err>tol and i<imax:
        wf, t, mis = run_mission_analysis(ac,mis,display)
        ac.designGoals.fuelMass = wf
        ac._update_mass()
        err = abs(wf-wfprev)
        wfprev = wf
        sys.stdout.write('>')
        i += 1
    sys.stdout.write('\n')
    return wf,mis

def run_test1():
    import aircraft_FW
    import mission_profile
    import matplotlib.pyplot as plt

    mis = mission_profile.load('profile3')
    ac = aircraft_FW.load('Baseline1')
    tol = 1.0
    err = tol+1
    imax = 20
    wfuel = list()
    i = 0
    wfprev = ac.designGoals.fuelMass
    while err>tol and i<imax:
        wf,t,mis = run_mission_analysis(ac,mis,False)
        ac.designGoals.fuelMass = wf
        ac._update_mass()
        i += 1
        err = abs(wf-wfprev)
        print wf
        wfuel.append(wf)
        wfprev = wf
    print i, err, wf
    print convert.kg_to_lb(ac.get_mass()), ac.get_mass()
    print convert.kg_to_lb(wf)
    print convert.kg_to_lb(ac.get_mass_empty())
    print mis
    #plt.plot(np.arange(i),wfuel,'rs-')
    #plt.show()

if __name__=="__main__":
    run_test1()